<script>
	import Vue from 'vue'
	import api from 'utils/api'
	import util from 'utils/util'
	import __config from 'config/env';


	import JimUtil from '@/utils/jim-util' // JLIM工具库

	// #ifdef APP-PLUS
	import APPUpdate from "@/public/APPUpdate/index.js"; //App版本更新
	// #endif

	export default {
		globalData: {
			shoppingCartCount: 0, //购物车数量
			tenantId: null, //租户Id
			appId: null, //公众号appId
			componentAppId: null, //第三方平台appid
			theme: { //主题定义
				backgroundColor: null, //背景颜色,支持渐变色
				themeColor: null, //主题颜色
				tabbarBackgroundColor: null, //tabbar背景颜色
				tabbarColor: null, //tabBar上的文字默认颜色
				tabbarSelectedColor: null, //tabBar上的文字选中时的颜色
				tabbarBorderStyle: null, //tabBar上边框的颜色
				tabbarItem: [], //tabBar明细设置
				showType: '1' //显示类型： 1 多店铺 2 单店铺
			},
			hasNetwork: true,
			JIM: null, //JLIMJMessage
			IMdata: {
				IMOpenLog: false,
				IMplatform: '5',
				IMoperationID: '',
				IMuserID: '',
				IMtoken: '',
				IMJSwsAddr: '', //wss连接地址
				IMloginStatus: false,
				IMconnectStatus: 0, // 服务器连接状态:0,:失败;1:成功;2:连接中
				IMmessageList: [], // 会话列表
				IMheartCheckTimer: null,
				IMcheckIMLoginOK: false,
			},
			WebViewUrl:__config.WebViewUrl
		},
		data() {
			return {
				tenantId: null, //租户Id(小程序只有在登录后才有值)
			};
		},
		onReady() {
			//顶部时间 电量颜色

			plus.navigator.setStatusBarStyle('light') // light（白色）、dark（黑色）
		},
		onLaunch: function() {
			// 1判断是否联网，2监听联网状态，3提示无网络
			// 1判断是否联网
			let that = this
			uni.getNetworkType({
				success: function(res) {
					if (res.networkType == 'none') {
						that.globalData.hasNetwork = false
					} else {
						that.globalData.hasNetwork = true
					}
				}
			});
			// #ifdef MP
			//小程序平台检测新版本
			this.updateManager();
			this.doLogin();
			// #endif
			// 原生app版本更新检测
			// #ifdef APP-PLUS
			APPUpdate();
			// #endif

			// #ifdef H5
			// H5平台获取参数中的租户ID、公众号appID,并存入globalData
			let local = location.href
			let tenantId = util.getUrlParam(local, "tenant_id");
			let appId = util.getUrlParam(local, "app_id");
			let componentAppId = util.getUrlParam(local, "component_appid");
			this.tenantId = tenantId;
			this.globalData.tenantId = tenantId;
			this.globalData.appId = appId;
			this.globalData.componentAppId = componentAppId;
			// #endif

			// #ifdef APP-PLUS
			// APP平台需要从配置文件中获取租户ID
			this.globalData.tenantId = __config.tenantId;
			this.tenantId = __config.tenantId;
			//获取购物车数量
			if (uni.getStorageSync('third_session')) {
				// this.shoppingCartCount();
			}
			// #endif
			//设置全局样式
			this.setGlobalStyle();

		},
		onShow: function() {
			console.log('App Show')
			// 初始化OpenIM
			// if (this.globalData.JIM) {
				// let that = this
				// JimUtil.showAPP()
			// }
		},
		onHide: function() {
			console.log('App Hide')
			// if (this.globalData.JIM) {
				// JimUtil.hideAPP()
			// }
		},
		methods: {
			setFavicon(h5Icon) {
				// #ifdef H5
				let that = this
				this.$nextTick(function() {
					var link = document.querySelector("link[rel*='icon']") || document.createElement('link');
					link.type = 'image/x-icon';
					link.rel = 'shortcut icon';
					link.href = h5Icon || '';
					document.getElementsByTagName('head')[0].appendChild(link);
				})
				// #endif
			},
			//设置全局样式
			setGlobalStyle() {
				uni.getSystemInfo({
					success: function(e) {
						// [2020-08-01]更新ColorUI 修复ios 状态栏错位
						// #ifndef MP
						Vue.prototype.StatusBar = e.statusBarHeight;
						if (e.platform == 'android') {
							Vue.prototype.CustomBar = e.statusBarHeight + 50;
						} else {
							Vue.prototype.CustomBar = e.statusBarHeight + 45;
						};
						// #endif
						// #ifdef MP-WEIXIN || MP-QQ
						Vue.prototype.StatusBar = e.statusBarHeight;
						let capsule = wx.getMenuButtonBoundingClientRect();
						if (capsule) {
							Vue.prototype.Custom = capsule;
							// Vue.prototype.capsuleSafe = uni.upx2px(750) - capsule.left + uni.upx2px(750) - capsule.right;
							Vue.prototype.CustomBar = capsule.bottom + capsule.top - e.statusBarHeight;
						} else {
							Vue.prototype.CustomBar = e.statusBarHeight + 50;
						}
						// #endif
						// #ifdef MP-ALIPAY
						Vue.prototype.StatusBar = e.statusBarHeight;
						Vue.prototype.CustomBar = e.statusBarHeight + e.titleBarHeight;
						// #endif
					}
				})
				// 优先显示获取缓存租户本地的主题数据
				let themeData = uni.getStorageSync('theme_mobile_' + this.tenantId);
				if (themeData) {
					this.initTheme(JSON.parse(themeData))
				}
				//获取主题装修配置
				this.initTheme()

				// api.themeMobileGet().then(res => {
				// 	console.log(res,'resssssssssss');
				// 	let tabberList = res.data.tabbarItem.info
				// 	let arr = []
				// 	if(tabberList&&tabberList.length){
				// 		tabberList.forEach((el,i)=>{
				// 			if(el.text == '消息'){
				// 				tabberList.splice(i,1)
				// 			}
				// 		})
				// 		tabberList.forEach((el,i)=>{
				// 			el.index = i
				// 		})
				// 		res.data.tabbarItem.info = tabberList
				// 	}
				// 	this.initTheme(res.data)
				// 	// 缓存到本地，方便下次进入时获取加载
				// 	uni.setStorage({
				// 		key: 'theme_mobile_' + this.tenantId,
				// 		data: JSON.stringify(res.data)
				// 	});
				// });
			},
			initTheme(themeMobile) {
				//定义默认配置
				let backgroundColor = 'gradual-scarlet';
				let themeColor = 'red';
				let tabbarBackgroundColor = '#ffffff';
				let tabbarColor = '#666666';
				let tabbarSelectedColor = 'red';
				let tabbarBorderStyle = '#black';
				let tabbarItem = [{
						index: 0,
						text: '首页',
						iconPath: '/static/public/img/icon-1/1-001.png',
						selectedIconPath: '/static/public/img/icon-1/1-002.png'
					},
					{
						index: 1,
						text: '我的',
						iconPath: '/static/public/img/icon-1/5-001.png',
						selectedIconPath: '/static/public/img/icon-1/5-002.png'
					},
					// {
					//   index: 2,
					//   text: '消息',
					//   iconPath: '/static/public/img/icon-1/3-001.png',
					//   selectedIconPath: '/static/public/img/icon-1/3-002.png'
					// },
					// {
					// 	index: 2,
					// 	text: '购物车',
					// 	iconPath: '/static/public/img/icon-1/4-001.png',
					// 	selectedIconPath: '/static/public/img/icon-1/4-002.png'
					// },
					// {
					// 	index: 3,
					// 	text: '我的',
					// 	iconPath: '/static/public/img/icon-1/5-001.png',
					// 	selectedIconPath: '/static/public/img/icon-1/5-002.png'
					// }
				]
				let showType = '1' //显示类型： 1 多店铺 2 单店铺
				//将默认配置换成后台数据
				// if (themeMobile) {
				// 	themeColor = themeMobile.themeColor
				// 	backgroundColor = themeMobile.backgroundColor
				// 	tabbarBackgroundColor = themeMobile.tabbarBackgroundColor
				// 	tabbarColor = themeMobile.tabbarColor
				// 	tabbarSelectedColor = themeMobile.tabbarSelectedColor
				// 	tabbarBorderStyle = themeMobile.tabbarBorderStyle
				// 	showType = themeMobile.showType
				// 	// #ifdef H5
				// 	// 设置浏览器favicon
				// 	this.setFavicon(themeMobile.h5Icon)
				// 	// #endif
				// }
				this.globalData.theme.backgroundColor = backgroundColor
				this.globalData.theme.themeColor = themeColor
				this.globalData.theme.tabbarBackgroundColor = tabbarBackgroundColor
				this.globalData.theme.tabbarColor = tabbarColor
				this.globalData.theme.tabbarSelectedColor = tabbarSelectedColor
				this.globalData.theme.tabbarBorderStyle = tabbarBorderStyle
				this.globalData.theme.tabbarItem = tabbarItem
				this.globalData.theme.showType = showType
				// if (themeMobile && themeMobile.tabbarItem && themeMobile.tabbarItem.info.length > 0) {
				// 	let tabbarItemInfo = themeMobile.tabbarItem.info
				// 	tabbarItemInfo.forEach(item => {
				// 		if (item.text) tabbarItem[item.index].text = item.text
				// 		if (item.iconPath) tabbarItem[item.index].iconPath = item.iconPath
				// 		if (item.selectedIconPath) tabbarItem[item.index].selectedIconPath = item.selectedIconPath
				// 	})
				// 	this.globalData.theme.tabbarItem = tabbarItem
				// }
				this.setTabBar()
			},

			// #ifdef MP
			//小程序平台检测新版本
			updateManager() {
				const updateManager = uni.getUpdateManager();
				updateManager.onUpdateReady(function() {
					uni.showModal({
						title: '更新提示',
						content: '新版本已经准备好，是否重启应用？',
						success(res) {
							if (res.confirm) {
								updateManager.applyUpdate();
							}
						}
					});
				});
			},
			// #endif

			//设置tabbar
			setTabBar() {
				let themeMobile = this.globalData.theme
				if (themeMobile.tabbarBackgroundColor) {
					//动态设置 tabBar 的整体样式
					uni.setTabBarStyle({
						backgroundColor: themeMobile.tabbarBackgroundColor,
						color: themeMobile.tabbarColor,
						selectedColor: themeMobile.tabbarSelectedColor,
						borderStyle: themeMobile.tabbarBorderStyle
					});
					let tabbarItem = themeMobile.tabbarItem;
					tabbarItem.forEach(item => {
						//动态设置 tabBar 某一项的内容
						let iconPath = item.iconPath;
						let selectedIconPath = item.selectedIconPath;
						// #ifdef H5
						//uni tabBar H5不支持http的图片,但是修改一下可以支持
						if (selectedIconPath.indexOf('http') != -1) { // 此判断包括 http 和 https
							let indexTemp = selectedIconPath.indexOf(':/') + 1;
							selectedIconPath = selectedIconPath.substring(indexTemp, selectedIconPath.length);
						}
						if (iconPath.indexOf('http') != -1) {
							let indexTemp = iconPath.indexOf(':/') + 1;
							iconPath = iconPath.substring(indexTemp, iconPath.length);
						}
						// #endif
						uni.setTabBarItem({
							index: item.index,
							text: item.text,
							iconPath: iconPath,
							selectedIconPath: selectedIconPath
						});
					})
				}
			},

			//获取购物车数量
			shoppingCartCount() {
				api.shoppingCartCount().then(res => {
					let shoppingCartCount = res.data;
					this.globalData.shoppingCartCount = shoppingCartCount + '';
					uni.setTabBarBadge({
						index: 2,
						text: this.globalData.shoppingCartCount + ''
					});
				});
			},
			//页面初始化方法，供每个页面调用
			initPage() {
				let that = this;
				return new Promise((resolve, reject) => {
					that.setTabBar()
					// 在线心跳
					// that.userOnlineHeartbeat()
					//小程序或公众号H5，每个页面都进行登录校验
					if (util.isMiniPg() || (that.globalData.appId && util.isWeiXinBrowser())) {
						if (!uni.getStorageSync('third_session')) {
							//无thirdSession，进行登录
							that.doLogin().then(res => {
								//初始化OpenIM
								that.initJIM();
								resolve("success");
							});
						} else {
							if (util.isMiniPg()) { //小程序需要检查登录态是否过期
								uni.checkSession({
									success() {
										//session_key 未过期，并且在本生命周期一直有效
										console.log('session_key 未过期')
										//初始化OpenIM
										that.initJIM();
										resolve("success");
									},
									fail() {
										// session_key 已经失效，需要重新执行登录流程
										console.log('session_key 已经失效')
										that.doLogin().then(res => {
											//初始化OpenIM
											that.initJIM();
											resolve("success");
										});
									}
								})
							} else {
								//初始化OpenIM
								// that.initJIM();
								resolve("success");
							}
						}
					} else {
						//初始化OpenIM
						// that.initJIM();
						resolve("success");
					}
				});
			},

			//登录操作
			doLogin() {
				// uni.showLoading({
				// 	title: '登录中'
				// });
				return new Promise((resolve, reject) => {
					// #ifdef MP-WEIXIN
					//微信小程序登录
					this.loginWxMa().then(res => {
						resolve("success");
					});
					// #endif
					// #ifdef H5
					//微信公众号H5
					if (util.isWeiXinBrowser()) {
						let local = location.href
						let code = util.getUrlParam(local, "code");
						let state = util.getUrlParam(local, "state");
						//授权code登录
						if (code) { //有code
							if (state == 'snsapi_base' || state == 'snsapi_userinfo') { //登录授权
								this.loginWxMp(code, state).then(res => {
									resolve("success");
								});
							}
						} else { //无code则发起网页授权
							//微信公众号H5，页面授权登录
							let appId = this.globalData.appId;
							let pages = getCurrentPages();
							let currentPage = pages[pages.length - 1];
							let route = currentPage.route;
							let redirectUri = location.href;
							let componentAppId_str = this.globalData.componentAppId ? '&component_appid=' + this
								.globalData.componentAppId : '';
							redirectUri = encodeURIComponent(redirectUri);
							let wx_url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + appId +
								'&redirect_uri=' + redirectUri + componentAppId_str +
								'&response_type=code&scope=snsapi_base&state=snsapi_base#wechat_redirect';
							location.href = wx_url;
						}
					}
					// #endif
				});
			},
			//微信小程序登录
			// #ifdef MP-WEIXIN
			loginWxMa() {
				return new Promise((resolve, reject) => {
					let that = this;
					uni.login({
						success: function(res) {
							if (res.code) {
								api.loginWxMa({
									jsCode: res.code
								}).then(res => {
									uni.hideLoading();
									let userInfo = res.data;
									uni.setStorageSync('third_session', userInfo.thirdSession);
									uni.setStorageSync('user_info', userInfo);
									// 获取购物车数量
									// that.shoppingCartCount();
									that.tenantId = userInfo.tenantId
									resolve("success");
								});
							}
						}
					});
				});
			},
			// #endif
			//公众号登录
			// #ifdef H5
			loginWxMp(code, state) {
				let that = this;
				return new Promise((resolve, reject) => {
					let that = this
					api.loginWxMp({
						jsCode: code,
						scope: state
					}).then(res => {
						//公众号h5网页授权时url会产生code、state参数，防止code、state被复制，需自动剔除
						let query = that.$Route.query;
						delete query.code;
						delete query.state;
						util.resetPageUrl(query);
						let userInfo = res.data;
						uni.setStorageSync('third_session', userInfo.thirdSession);
						uni.setStorageSync('user_info', userInfo);
						//获取购物车数量
						// that.shoppingCartCount();
						resolve("success");
					}).catch(res => {

					});
				});
			},
			// #endif
			//初始化OpenIM
			initJIM() {
				let that = this
				return new Promise((resolve, reject) => {
					//获取用户信息
					let userInfo = uni.getStorageSync('user_info')
					let thirdSession = uni.getStorageSync('third_session')
					//还不是商城用户，不登录JLIM
					if (!userInfo || !userInfo.id || !thirdSession) {
						console.log("还不是商城用户，不登录JLIM")
						resolve("success");
						return
					}
					if (this.globalData.JIM && this.globalData.IMdata && this.globalData.IMdata.IMloginStatus &&
						this.globalData.IMdata.IMconnectStatus == 1) { //OpenIM已经初始化，直接登录
						if (this.globalData.IMdata.IMOpenLog) console.log("IM已经登录")
						// JimUtil.checkLoginStatus()
						resolve("success");
						return
					} else {
						// 初始化
						// JimUtil.initOpenIM().then(() => {
						// 	resolve("success");
						// }).catch(() => {
						// 	resolve("success");
						// })
					}
				});
			},
			userOnlineHeartbeat(cancel) {
				// 登录后每隔5分钟自动调用接口一次,统计在线人数,登出后取消调用
				if (cancel) {
					console.log("************ 用户在线统计心跳已取消 ************");
					if (this.globalData.userOnlineTimer) {
						clearInterval(this.globalData.userOnlineTimer)
						this.globalData.userOnlineTimer = null
					}
					let userInfo = uni.getStorageSync('user_info')
					if (userInfo) {
						uni.removeStorageSync('user_online_heartbeat_request_time_' + userInfo.id)
					}
				} else if (!this.globalData.userOnlineTimer) {
					let userInfo = uni.getStorageSync('user_info')
					let thirdSession = uni.getStorageSync('third_session')
					// 如果已登录就进行心跳请求
					if (userInfo && userInfo.id && thirdSession) {
						// 当前时间大于等于5分钟才会去请求第二次心跳
						let intervalTime = 5 * 60 * 1000
						let userOnlineHeartbeatTimer = function(userId, intervalTime) {
							let userOnlineRequestTime = uni.getStorageSync('user_online_heartbeat_request_time_' +
								userId)
							let nowTime = new Date().getTime()
							let lastTime = nowTime - userOnlineRequestTime
							if (lastTime >= intervalTime) {
								// console.log("************ 用户在线统计心跳 ************");
								api.userOnlineHeartbeat().then(res => {
									uni.setStorageSync('user_online_heartbeat_request_time_' + userId, nowTime)
								});
							}
							// else {
							// 表示可能已有其他页面已经请求过该请求了
							// console.log("************ 用户在线统计心跳请求时间间隔过快 ************");
							// }
						}
						userOnlineHeartbeatTimer(userInfo.id, intervalTime)
						this.globalData.userOnlineTimer = setInterval(userOnlineHeartbeatTimer, intervalTime, userInfo.id,
							intervalTime)
					}
				}
			}

		}
	};
</script>
<style lang="scss">
	/* #ifndef APP-PLUS-NVUE */
	@import "./app.css";
	@import "./style/common.scss";

	/* #endif */
</style>